import Discord from "@renderer/assets/icons/discord.svg?url";
import Github from "@renderer/assets/icons/github.svg?url";
import Twitter from "@renderer/assets/icons/twitter.svg?url";
import { ModelIcon } from "@renderer/components/business/model-icon";
import { NewVersionModal } from "@renderer/components/business/new-version-modal";
import { Button } from "@renderer/components/ui/base/button";
import { Link } from "@renderer/components/ui/base/link";
import { Separator } from "@renderer/components/ui/base/separator";
import { cn } from "@renderer/lib/utils";
import logger from "@shared/logger/renderer-logger";
import { motion } from "motion/react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import packageJson from "../../../../../package.json";

const { shellService } = window.service;

// Konami code sequence: ↑↑↓↓←→←→BA Space
const KONAMI_CODE = [
  "ArrowUp",
  "ArrowUp",
  "ArrowDown",
  "ArrowDown",
  "ArrowLeft",
  "ArrowRight",
  "ArrowLeft",
  "ArrowRight",
  "KeyB",
  "KeyA",
  "Space",
];

export function AboutSettings() {
  const { t } = useTranslation("translation", {
    keyPrefix: "settings.about-settings",
  });
  const navigate = useNavigate();

  const [isActivated, setIsActivated] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const keySequenceRef = useRef<string[]>([]);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  const { productName, version, homepage } = packageJson;

  const handleLinkClick = (url: string) => {
    shellService.openExternal(url);
  };

  const resetSequence = useCallback(() => {
    keySequenceRef.current = [];
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
  }, []);

  const checkKonamiCode = useCallback(
    (sequence: string[]) => {
      logger.info("Checking sequence", {
        sequence,
        length: sequence.length,
        targetLength: KONAMI_CODE.length,
      });

      if (sequence.length > KONAMI_CODE.length) {
        logger.info("Sequence too long, resetting");
        resetSequence();
        return;
      }

      // Check if current sequence matches the beginning of Konami code
      const isMatching = sequence.every(
        (key, index) => key === KONAMI_CODE[index],
      );

      logger.info("Sequence matching check", { isMatching });

      if (!isMatching) {
        logger.info("Sequence not matching, resetting");
        resetSequence();
        return;
      }

      // If complete sequence matches
      if (sequence.length === KONAMI_CODE.length) {
        logger.info("Konami code activated! Navigating to log viewer");
        setIsActivated(true);

        // Add a longer delay to let the rotation animation complete
        setTimeout(() => {
          navigate("/settings/log-viewer");
        }, 1000);
      }
    },
    [navigate, resetSequence],
  );

  const handleKeyDown = useCallback(
    (event: KeyboardEvent) => {
      // Ignore key events when input fields are focused
      if (
        event.target instanceof HTMLInputElement ||
        event.target instanceof HTMLTextAreaElement
      ) {
        return;
      }

      keySequenceRef.current = [...keySequenceRef.current, event.code];
      logger.info("Key pressed", {
        key: event.code,
        sequence: keySequenceRef.current,
        target: KONAMI_CODE,
      });
      checkKonamiCode(keySequenceRef.current);

      // Reset sequence after 2 seconds of inactivity
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      timeoutRef.current = setTimeout(resetSequence, 2000);
    },
    [checkKonamiCode, resetSequence],
  );

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);

    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [handleKeyDown]);

  const socialMedias = [
    {
      name: "Github",
      icon: Github,
      action: () => handleLinkClick("https://github.com/302ai"),
    },
    {
      name: "Twitter",
      icon: Twitter,
      action: () => handleLinkClick("https://x.com/302aiofficial"),
    },
    {
      name: "Discord",
      icon: Discord,
      action: () => handleLinkClick("https://discord.com/invite/4fgQ4M6ypq"),
    },
  ] as const;

  const footerLinks = [
    {
      id: 1,
      name: t("help-center.title"),
      action: () => handleLinkClick("https://help.302.ai/"),
    },
    {
      id: 2,
      name: t("terms-of-service.title"),
      action: () => handleLinkClick("https://302.ai/terms/"),
    },
    {
      id: 3,
      name: t("privacy-policy.title"),
      action: () => handleLinkClick("https://302.ai/privacy/"),
    },
  ] as const;

  return (
    <motion.div
      className={cn(
        "mx-auto flex h-full flex-1 flex-col items-center justify-between pb-9",
      )}
      animate={isActivated ? { rotateY: 360 } : {}}
      transition={{ duration: 1.0, ease: "easeInOut" }}
      exit={{ opacity: 0, rotateY: 360 }}
    >
      <div className="flex flex-1 flex-col items-center justify-center gap-6">
        <div className="flex flex-col items-center gap-y-[22px] text-center">
          <ModelIcon modelName="302" className="size-[62px]" />
          <div className="flex flex-col gap-y-[7px]">
            <span className="font-[500] text-xl">{productName}</span>
            <div className="flex flex-col space-y-2">
              <span className="text-muted-fg text-sm">
                {t("version")} {version}
              </span>
              <Button intent="secondary" onPress={() => setIsModalOpen(true)}>
                🎉 {t("new-version-released.title")} 🎉
              </Button>
            </div>
          </div>
        </div>

        <p className="mx-auto max-w-xl text-center text-muted-fg text-sm leading-relaxed">
          {t("description.content")}
          <Link
            onClick={() => handleLinkClick(homepage)}
            className="inline-flex cursor-pointer items-center gap-1 text-primary text-sm hover:underline"
          >
            {homepage}
          </Link>
        </p>
      </div>

      <div className="flex items-center gap-4">
        <div className="flex items-center gap-4">
          {socialMedias.map((item) => (
            <Button
              key={item.name}
              className="size-7 hover:bg-transparent"
              intent="plain"
              size="sq-xs"
              onPress={item.action}
            >
              <img src={item.icon} alt={item.name} />
            </Button>
          ))}
        </div>
        <div className="flex items-center gap-x-4">
          {footerLinks.map((item, index) => (
            <div key={item.id} className="flex items-center gap-x-4">
              <Link
                onPress={item.action}
                className="cursor-pointer text-muted-fg text-sm hover:text-fg"
              >
                {item.name}
              </Link>
              <Separator
                orientation="vertical"
                className={cn("h-5 w-0.5 bg-muted-fg", {
                  "opacity-0": index === footerLinks.length - 1,
                })}
              />
            </div>
          ))}
        </div>
      </div>

      <NewVersionModal isOpen={isModalOpen} onOpenChange={setIsModalOpen} />
    </motion.div>
  );
}
